package com.yanqu.road.server.manager.activity.xingyou.inter.grid;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.entity.activity.youxing.*;
import com.yanqu.road.entity.activity.youxing.config.XingYouShanShuiGridInfo;
import com.yanqu.road.entity.enums.eChatContentType;
import com.yanqu.road.entity.log.cross.xingyou.LogCrossXingYouBattle;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.helper.RandomWeightConfigHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.activity.CommonTeamProto;
import com.yanqu.road.pb.activity.XingYouShanShuiProto;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeam;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeamActivity;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeamMgr;
import com.yanqu.road.server.manager.activity.xingyou.ConfirmHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.CrossXingYouActivity;
import com.yanqu.road.server.manager.activity.xingyou.DiceHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.inter.GridHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.inter.IXingYouGridHandler;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 挑战格
 */
public class TzGridHandler implements IXingYouGridHandler {

    @Override
    public void handle(XingYouShanShuiGridInfo gridInfo, int pos, int gridId, int endPos, boolean fly, DiceHandleResult result) {

        //是否停留
        boolean stop = pos == endPos;
        if(!stop){
            return;
        }

        CrossXingYouShanShuiUserData userData = result.getUserData();
        int teamId = userData.getTeamId();

        Integer gid = result.getActivity().getConfig().getSHANSHUI_MAP().get(pos);
        if(gid != 17){
            return;
        }
        XingYouShanShuiProto.ShanShuiEventInfo.Builder eventBuilder = XingYouShanShuiProto.ShanShuiEventInfo.newBuilder();
        eventBuilder.setPosition(pos);
        eventBuilder.setGridId(gridId);

        Property fixedReward = result.getActivity().getGridInfoFixedReward(result.getUserData(), gridInfo, true);
        eventBuilder.setFixedReward(PropertyHelper.parsePropertyToString(fixedReward));

        Property reward = new Property();
        reward.addProperty(fixedReward);

        eventBuilder.setBaseReward(PropertyHelper.parsePropertyToString(reward));
        result.getActivity().calRewardBuff(result.getUserData(), reward, false, 0);


        CrossXingYouShanShuiTeamMapData mapData = result.getActivity().getCrossXingYouShanShuiTeamMapData(userData.getTeamId(), pos);
        ShanShuiGridParam gridParam = new ShanShuiGridParam(gridId, pos, false, userData.isDrift());
        synchronized (result.getActivity().getTeamLocker(teamId)){
            if(mapData.getTzUserId() == 0){
                //随机一个玩家
                mapData.setTzUserId(result.getActivity().randomTzEmeny(teamId));
            }
            if(mapData.getTzUserId() > 0){
                eventBuilder.setEventParam(1);
                gridParam.setEventParam(1);
            }else {
                eventBuilder.setEventParam(0);
                gridParam.setEventParam(0);
            }
        }

        eventBuilder.setAward(PropertyHelper.parsePropertyToString(reward));

        GridHandleResult gridHandleResult = new GridHandleResult();
        gridHandleResult.setGridParam(gridParam);
        gridHandleResult.setBuilder(eventBuilder);
        result.getGridHandleResultList().add(gridHandleResult);
    }

    @Override
    public void confirm(XingYouShanShuiGridInfo gridInfo, CrossXingYouShanShuiUserData userData, ConfirmHandleResult handleResult, long targetId, boolean isDrift) {

        CrossXingYouActivity activity = handleResult.getActivity();
        CommonTeamActivity teamActivity = CommonTeamMgr.getActivity(activity.getConfig().getActivityInfo().getActivityId(), userData.getGroupId());
        CrossXingYouTargetMarkData markData = null;
        long tzUserId;
        synchronized (activity.getTeamData(userData.getTeamId())){
            ShanShuiGridParam gridParam = userData.getGridParam();
            if(userData.isDrift()){
                gridParam = userData.getDriftGridParam();
            }
            if(gridParam.isHandled() || gridParam.getId() != 17){
                handleResult.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
                return;
            }
            CrossXingYouShanShuiTeamMapData mapData = activity.getCrossXingYouShanShuiTeamMapData(userData.getTeamId(), gridParam.getMapIndex());
            if(mapData.getTzUserId() == 0){
                handleResult.setRet(GameErrorCode.E_XING_YOU_SHAN_SHUI_INFO_OUT_TIME);
                return;
            }

            tzUserId = mapData.getTzUserId();

            if(targetId != tzUserId){
//                handleResult.setRet(GameErrorCode.E_XING_YOU_SHAN_SHUI_INFO_OUT_TIME);
//                return;
            }

            XingYouShanShuiProto.ShanShuiBattleRecordMsg.Builder battleBuilder = activity.battle(userData.getUserId(), mapData.getTzUserId(), new ArrayList<>(), 0);

            CrossXingYouShanShuiUserData targetUserData = handleResult.getActivity().getUserData(tzUserId);
            CommonTeam team = CommonTeamMgr.getTeam(targetUserData.getActivityId(), 0, targetUserData.getTeamId());

            if(!battleBuilder.getIsWin()){
                //标记
                markData = new CrossXingYouTargetMarkData();
                markData.setGroupId(userData.getGroupId());
                markData.setInsertOption();
                markData.setActivityId(activity.getConfig().getActivityInfo().getActivityId());
                markData.setTeamId(userData.getTeamId());
                markData.setUserId(userData.getUserId());
                markData.setPos(gridParam.getMapIndex());
                markData.setTzList(new ArrayList<>());

                XingYouShanShuiProto.ShanShuiBattleMainMsg enemy = battleBuilder.getPlayers(1);
                markData.setTargetUserId(tzUserId);
                markData.setMaxTargetHp(enemy.getMaxHp());
                markData.setTargetHp(battleBuilder.getEnemyHp());

                markData.setLogTime(System.currentTimeMillis());
                //当天有效
                markData.setExpireTime(DateHelper.getTodayZeroTime() + DateHelper.DAY_SECONDS);
                activity.addCrossXingYouTargetMarkData(markData);

                //替换
                mapData.setTzUserId(handleResult.getActivity().randomTzEmeny(userData.getTeamId()));

                //失败按比例获得奖励
                Property property = new Property();
                if(!"0".equals(gridInfo.getReward2())){
                    property = PropertyHelper.parseStringToProperty(gridInfo.getReward2());
                    BigDecimal decimal = BigDecimal.valueOf(enemy.getHp() - battleBuilder.getEnemyHp()).divide(BigDecimal.valueOf(enemy.getMaxHp()), 3, BigDecimal.ROUND_UP);
                    property.rideProperty(decimal);
                }
                handleResult.getBuilder().setBaseReward(PropertyHelper.parsePropertyToString(property));

                handleResult.getActivity().calRewardBuff(userData, property, false, 0);

                handleResult.getReward().addProperty(property);

                //挑战失败-队伍日志
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(tzUserId);
                CrossXingYouShanShuiTeamActionLogData actionLogData = handleResult.getActivity().createActionLogData(userData, XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_CHALLENGE_FAIL, PropertyHelper.parsePropertyToString(property),
                        Arrays.asList(String.valueOf(userData.getRoleId()), team == null ? "" : team.getTeamName(), userBaseInfo == null ? "" : userBaseInfo.getNickName()));
                handleResult.getActionLogDataList().add(actionLogData);

                CrossXingYouShanShuiUserData tzUserData = handleResult.getActivity().getUserData(tzUserId);
                LogCrossXingYouBattle log = new LogCrossXingYouBattle(
                        userData.getActivityId(),
                        userData.getUserId(),
                        userData.getTeamId(),
                        gridInfo.getId(),
                        gridParam.getMapIndex(),
                        userData.getMapTeamId(),
                        tzUserId,
                        tzUserData.getTeamId(),
                        1,
                        battleBuilder.getPlayers(0).getMaxHp(),
                        battleBuilder.getPlayers(1).getHp() - battleBuilder.getEnemyHp(),
                        battleBuilder.getEnemyHp(),
                        battleBuilder.getIsWin() ? 1 : 0,
                        property.getCountByGoodsId(handleResult.getActivity().getConfig().getSHANSHUI_SILVER_COIN_ID()).intValue(),
                        property.getCountByGoodsId(handleResult.getActivity().getConfig().getSHANSHUI_GOLD_COIN_ID()).intValue(),
                        PropertyHelper.parsePropertyToString(property)
                );
                handleResult.getAutoLogList().add(log);

            }else {

                mapData.setTzUserId(handleResult.getActivity().randomTzEmeny(userData.getTeamId()));

                Property allReward = new Property();

                //按比例获得奖励
                if(!"0".equals(gridInfo.getReward2())){
                    Property property = PropertyHelper.parseStringToProperty(gridInfo.getReward2());
                    allReward.addProperty(property);
                }

                String reward = handleResult.getActivity().getCheReward();
                if(!StringUtils.isNullOrEmpty(reward)) {
                    allReward.addProperty(PropertyHelper.parseStringToProperty(reward));
                }

                handleResult.getBuilder().setBaseReward(PropertyHelper.parsePropertyToString(allReward));

                handleResult.getActivity().calRewardBuff(userData, allReward, false, 0);

                //挑战成功-队伍日志
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(tzUserId);
                CrossXingYouShanShuiTeamActionLogData actionLogData = handleResult.getActivity().createActionLogData(userData, XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_CHALLENGE_SUCCESS,
                        PropertyHelper.parsePropertyToString(allReward),
                        Arrays.asList(String.valueOf(userData.getRoleId()), team == null ? "" : team.getTeamName(), userBaseInfo == null ? "" : userBaseInfo.getNickName()));
                handleResult.getActionLogDataList().add(actionLogData);

                handleResult.getReward().addProperty(allReward);

                CrossXingYouShanShuiUserData tzUserData = handleResult.getActivity().getUserData(tzUserId);
                LogCrossXingYouBattle log = new LogCrossXingYouBattle(
                        userData.getActivityId(),
                        userData.getUserId(),
                        userData.getTeamId(),
                        gridInfo.getId(),
                        gridParam.getMapIndex(),
                        userData.getMapTeamId(),
                        tzUserId,
                        tzUserData.getTeamId(),
                        1,
                        battleBuilder.getPlayers(0).getMaxHp(),
                        battleBuilder.getPlayers(1).getHp() - battleBuilder.getEnemyHp(),
                        battleBuilder.getEnemyHp(),
                        battleBuilder.getIsWin() ? 1 : 0,
                        allReward.getCountByGoodsId(handleResult.getActivity().getConfig().getSHANSHUI_SILVER_COIN_ID()).intValue(),
                        allReward.getCountByGoodsId(handleResult.getActivity().getConfig().getSHANSHUI_GOLD_COIN_ID()).intValue(),
                        reward
                );
                handleResult.getAutoLogList().add(log);

            }

            handleResult.getBuilder().setBattleRecord(battleBuilder);
            handleResult.getBuilder().setIsWin(battleBuilder.getIsWin());

            gridParam.setHandled(true);
        }

        if(markData != null){
            //队伍聊天协助

            CommonTeamProto.CommonTeamChatMsg.Builder chatMsgBuilder = teamActivity.createTeamChatMsg(userData.getUserId(), CommonTeamProto.CommonTeamChatTypeEnum.ACTIVITY_VALUE, eChatContentType.Common.getContentType(), "");
            Map<String, Object> params = new HashMap<>();
            params.put("type", 6);
            params.put("logId", markData.getId());
            chatMsgBuilder.setExtraParams(JSON.toJSONString(params));
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(tzUserId);
            if(userBaseInfo != null){
                chatMsgBuilder.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            }
            CommonTeam team = teamActivity.getTeam(userData.getTeamId());
            team.sendTeamChatMsg(chatMsgBuilder.build());
        }

    }
}
